//
//  ChangePaymentPwdViewController.m
//  CBT
//
//  Created by Mr.Zhang on 2018/11/22.
//  Copyright © 2018 Mr.Zhang. All rights reserved.
//

#import "ChangePaymentPwdViewController.h"

#import "ChangePayMentCell.h"

#import "ChangePaymentViewModel.h"

@interface ChangePaymentPwdViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) ChangePaymentViewModel *viewModel;

@property (nonatomic,strong) id timer;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) UIButton *subMitBtn;

@end

@implementation ChangePaymentPwdViewController

#pragma mark - VC Life

- (void)viewDidLoad {
    [super viewDidLoad];

    [self showInfoMsg];
    
    [self inputAction];
    
    [self outPutAction];
}

-(void)dealloc{
    if (_timer) {
        dispatch_source_cancel(_timer);
    }
}

- (void)showInfoMsg
{
    self.tableView.backgroundColor = UIColorFromRGB(0xf1f1f1);
    
    self.navigationItem.title = kLocalizedString(@"修改支付密码", nil);
    
    self.tableView.tableFooterView = [UIView new];
    
    if (@available(iOS 11.0, *)){
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.tableView.estimatedRowHeight           = 230;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    
    [self.tableView addSubview:self.subMitBtn];
   
    UITapGestureRecognizer *tableViewGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tableViewTouchInSide)];
    tableViewGesture.numberOfTapsRequired = 1;
    tableViewGesture.cancelsTouchesInView = NO;
    [self.tableView addGestureRecognizer:tableViewGesture];
}

- (void)tableViewTouchInSide
{
    [self.view endEditing:YES];
}

#pragma mark - sendCode

-(void)sendCodeActionWithBtn:(UIButton *)btn
{
    __block NSInteger second = 60;
    //全局队列    默认优先级
    dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //定时器模式  事件源
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, quene);
    
    _timer = timer;
    
    //NSEC_PER_SEC是秒，＊1是每秒
    dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), NSEC_PER_SEC * 1, 0);
    //设置响应dispatch源事件的block，在dispatch源指定的队列上运行
    dispatch_source_set_event_handler(timer, ^{
        //回调主线程，在主线程中操作UI
        dispatch_async(dispatch_get_main_queue(), ^{
            if (second > 0) {
                btn.userInteractionEnabled = NO;
                btn.backgroundColor = UIColorFromRGB(0xd3d8fd);
                [btn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
                btn.layer.borderWidth = 0;
                [btn setTitle:[NSString stringWithFormat:@"%lds",(long)second] forState:UIControlStateNormal];
                second--;
            }else{
                //这句话必须写否则会出问题
                btn.userInteractionEnabled = YES;
                btn.backgroundColor = [UIColor whiteColor];
                [btn setTitleColor:UIColorFromRGB(0x7889ff) forState:(UIControlStateNormal)];
                btn.layer.borderWidth = 1;
                dispatch_source_cancel(timer);
                [btn setTitle:@"发送验证码" forState:UIControlStateNormal];
            }
        });
    });
    //启动源
    dispatch_resume(timer);
}

#pragma mark - Input

- (void)inputAction
{
    @weak(self)
    
    ChangePayMentCell *cell = ((ChangePayMentCell *)[self_weak_.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]);
    
    //确定修改密码
    [[self.subMitBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self_weak_.view endEditing:YES];
        [self_weak_ startClearBgColorLoading];
        
        NSString *areaStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"area"];
        NSString *phoneStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"];
        NSString *emailStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"emailAddress"];

        if (emailStr.length < 5) {
            [self_weak_.viewModel.subMitCommand execute:@{@"area":areaStr,@"ID":phoneStr,@"code":cell.codeTextField.text,@"password":cell.pwdTextField.text}];
        }
        else{
            [self_weak_.viewModel.subMitCommand execute:@{@"ID":emailStr,@"code":cell.codeTextField.text,@"password":cell.pwdTextField.text}];
        }
    }];
    
    //发送验证码
    [[cell.codeBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self_weak_.view endEditing:YES];
        [self_weak_ startClearBgColorLoading];
        
        NSString *areaStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"area"];
        NSString *phoneStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"];
        NSString *emailStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"emailAddress"];
        
        if (emailStr.length < 5) {
            [self_weak_.viewModel.sendCodeCommand execute:@{@"code":areaStr,@"ID":phoneStr}];
        }
        else{
            [self_weak_.viewModel.sendCodeCommand execute:@{@"ID":emailStr}];
        }
        
    }];
}

#pragma mark - OutPut

- (void)outPutAction
{
    @weak(self)
    
    ChangePayMentCell *cell = ((ChangePayMentCell *)[self_weak_.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]);
    
    //修改登录密码成功
    [self.viewModel.subMitCommand.executionSignals.switchToLatest subscribeNext:^(id  _Nullable x) {
        [self_weak_ stopLoading];
        [self_weak_.navigationController popViewControllerAnimated:YES];
    }];
    
    [self.viewModel.subMitCommand.errors subscribeNext:^(NSError * _Nullable x) {
        [self_weak_ stopLoading];
    }];
    
    //发送验证码成功
    [self.viewModel.sendCodeCommand .executionSignals.switchToLatest subscribeNext:^(id  _Nullable x) {
        [self_weak_ stopLoading];
        [self_weak_ sendCodeActionWithBtn:cell.codeBtn];
    }];
    
    [self.viewModel.sendCodeCommand.errors subscribeNext:^(NSError * _Nullable x) {
        [self_weak_ stopLoading];
    }];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChangePayMentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    
    cell.phoneTextField.userInteractionEnabled = NO;
    NSString *areaStr  = [[NSUserDefaults standardUserDefaults] objectForKey:@"area"];
    NSString *phoneStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"];
    NSString *emailStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"emailAddress"];
    
    if (emailStr.length < 5) {
        cell.phoneTextField.text = [NSString stringWithFormat:@"+%@ %@",areaStr, phoneStr];
    }
    else {
        cell.phoneTextField.text = emailStr;
    }
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 174;
}

#pragma mark - Lazy

- (UIButton *)subMitBtn
{
    if (!_subMitBtn) {
        _subMitBtn = [[UIButton alloc]initWithFrame:CGRectMake(25, 202, ScreenNarrowSide - 50, 40)];
        [_subMitBtn setTitle:kLocalizedString(@"确定", nil) forState:(UIControlStateNormal)];
        [_subMitBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
       
        _subMitBtn.backgroundColor = UIColorFromRGB(0xff5101);
        _subMitBtn.layer.cornerRadius = 20;
        _subMitBtn.layer.masksToBounds = YES;
        _subMitBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    }
    return _subMitBtn;
}

- (ChangePaymentViewModel *)viewModel
{
    if (!_viewModel) {
        _viewModel = [[ChangePaymentViewModel alloc]init];
    }
    return _viewModel;
}

@end
